<template>
  <div class="point-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="点位名称">
          <el-input v-model="queryParams.name" placeholder="请输入点位名称" clearable />
        </el-form-item>
        <el-form-item label="所属区域">
          <el-select v-model="queryParams.areaId" placeholder="请选择区域" clearable>
            <el-option
              v-for="area in areaList"
              :key="area.id"
              :label="area.name"
              :value="area.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 点位列表 -->
    <el-table
      v-loading="loading"
      :data="pointList"
      border
      style="width: 100%"
    >
      <el-table-column prop="name" label="点位名称" />
      <el-table-column prop="areaName" label="所属区域" />
      <el-table-column prop="address" label="详细地址" show-overflow-tooltip />
      <el-table-column prop="machineCount" label="售货机数量" width="100" align="center" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 点位表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="pointFormRef"
        :model="pointForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="点位名称" prop="name">
          <el-input v-model="pointForm.name" placeholder="请输入点位名称" />
        </el-form-item>
        <el-form-item label="所属区域" prop="areaId">
          <el-select v-model="pointForm.areaId" placeholder="请选择区域">
            <el-option
              v-for="area in areaList"
              :key="area.id"
              :label="area.name"
              :value="area.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="pointForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPointList, addPoint, updatePoint, deletePoint } from '@/api/point'
import { getAreaList } from '@/api/area'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  areaId: undefined
})

// 列表数据
const loading = ref(false)
const pointList = ref([])
const total = ref(0)
const areaList = ref([])

// 获取点位列表
const getList = async () => {
  try {
    loading.value = true
    const { data } = await getPointList(queryParams)
    pointList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取点位列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取区域列表
const getAreas = async () => {
  try {
    const { data } = await getAreaList()
    areaList.value = data
  } catch (error) {
    console.error('获取区域列表失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.name = ''
  queryParams.areaId = undefined
  handleQuery()
}

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('') // add 或 edit
const dialogTitle = ref('')
const pointFormRef = ref()
const pointForm = reactive({
  id: undefined,
  name: '',
  areaId: undefined,
  address: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入点位名称', trigger: 'blur' }
  ],
  areaId: [
    { required: true, message: '请选择所属区域', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增点位'
  dialogVisible.value = true
  pointForm.id = undefined
  pointForm.name = ''
  pointForm.areaId = undefined
  pointForm.address = ''
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑点位'
  dialogVisible.value = true
  pointForm.id = row.id
  pointForm.name = row.name
  pointForm.areaId = row.areaId
  pointForm.address = row.address
}

// 提交表单
const submitForm = async () => {
  if (!pointFormRef.value) return
  
  await pointFormRef.value.validate()
  
  try {
    if (dialogType.value === 'add') {
      await addPoint(pointForm)
      ElMessage.success('新增成功')
    } else {
      await updatePoint(pointForm)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('保存点位失败:', error)
  }
}

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除点位"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deletePoint(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除点位失败:', error)
    }
  })
}

onMounted(() => {
  getList()
  getAreas()
})
</script>

<style scoped>
.point-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.form-inline {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style> 